/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.dao;

import han.bifang.common.entity.SoaUsergroup;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;
import han.bifang.common.persist.dao.DaoManager;
import han.bifang.common.persist.page.Page;
import han.bifang.common.persist.page.PagedQuery;
import han.bifang.common.persist.tx.Tx;
import han.bifang.common.persist.tx.TxManager;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class GroupDao {

	public static String createUsergroup(SoaUsergroup group)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaUsergroup s where s.groupName = ?";
			List groups = DaoManager.getDao().find(hql, group.getGroupName());
			if (groups.size() > 0) {
				throw new BifangException(
						BifangErrorCode.GROUP_NAME_EXIST_ERROR,
						"Usergroup name '" + group.getGroupName()
								+ "' already exists");
			}
			DaoManager.getDao().save(group);
			DaoManager.getDao().flush();
			tx.commit();
			return group.getId();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(GroupDao.class);
			logger.error("UsergroupDao.createUsergroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"createUsergroup() error", e);
		} finally {
			tx.end();
		}

	}

	public static void modifyUsergroup(SoaUsergroup group)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaUsergroup s where s.groupName = ?";
			List groups = DaoManager.getDao().find(hql, group.getGroupName());
			if (groups.size() > 0) {
				SoaUsergroup u = (SoaUsergroup) groups.get(0);
				if (!u.getId().equals(group.getId()))
					throw new BifangException(
							BifangErrorCode.GROUP_NAME_EXIST_ERROR,
							"Usergroup name '" + group.getGroupName()
									+ "' already exists");
			}
			DaoManager.getDao().merge(group);
			DaoManager.getDao().flush();
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(GroupDao.class);
			logger.error("UsergroupDao.modifyUsergroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"modifyUsergroup() error", e);
		} finally {
			tx.end();
		}

	}

	public static SoaUsergroup getUsergroup(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaUsergroup u = (SoaUsergroup) DaoManager.getDao().get(
					SoaUsergroup.class, id);
			tx.commit();

			return u;
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(GroupDao.class);
			logger.error("UsergroupDao.getUsergroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getUsergroup() error", e);
		} finally {
			tx.end();
		}

	}

	public static void removeUsergroup(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaUsergroup u = (SoaUsergroup) DaoManager.getDao().get(
					SoaUsergroup.class, id);
			DaoManager.getDao().delete(u);
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(GroupDao.class);
			logger.error("UsergroupDao.removeUsergroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeUsergroup() error", e);
		} finally {
			tx.end();
		}

	}

	public static List findGroupsByPage(String groupName, int page, int pageSize)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();

			String hql = "from SoaUsergroup u where 1 = 1";
			if (groupName != null) {
				hql = hql + " and u.groupName like '%" + groupName + "%'";
			}

			PagedQuery pq = new PagedQuery(hql, page, pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();

			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("UserDao.findGroupsByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupsByPage() error", e);
		} finally {
			tx.end();
		}
	}

	public static List<SoaUsergroup> findGroupsNotOfUserByPage(String userId,
			String groupName, int page, int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			if(groupName == null)
				groupName = "";

			String hql = "from SoaUsergroup u where u.groupName like '%"
					+ groupName
					+ "%' and u.id not in (select u1.id  from SoaUsergroup u1, SoaUsergroupUserRel r where r.compId.userId = '"
					+ userId + "' "
					+ " and r.compId.usergroupId = u1.id)";

			PagedQuery pq = new PagedQuery(hql, page, pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();

			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("UserDao.findGroupsNotOfUserByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupsNotOfUserByPage() error", e);
		} finally {
			tx.end();
		}
	}
	
	public static List<SoaUsergroup> findGroupsNotOfRoleByPage(String roleId,
			String groupName, int page, int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			if(groupName == null)
				groupName = "";

			String hql = "from SoaUsergroup u where u.groupName like '%"
					+ groupName
					+ "%' and u.id not in (select u1.id  from SoaUsergroup u1, SoaUsergroupRoleRel r where r.compId.roleId = '"
					+ roleId + "' "
					+ " and r.compId.usergroupId = u1.id)";

			PagedQuery pq = new PagedQuery(hql, page, pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();

			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("UserDao.findGroupsNotOfRoleByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupsNotOfRoleByPage() error", e);
		} finally {
			tx.end();
		}
	}

	public static List findGroupByUserId(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select u  from SoaUsergroup u, SoaUsergroupUserRel r where r.compId.userId = ?"
					+ " and r.compId.usergroupId = u.id";
			List ret = DaoManager.getDao().find(hql, id);

			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("GroupDao.findGroupByUserId()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupByUserId() error", e);
		} finally {
			tx.end();
		}

	}

	public static List findGroupsByRoleId(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select u  from SoaUsergroup u, SoaUsergroupRoleRel r where r.compId.roleId = ?"
					+ " and r.compId.usergroupId = u.id";
			List ret = DaoManager.getDao().find(hql, id);

			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("GroupDao.findGroupByRoleId()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupByRoleId() error", e);
		} finally {
			tx.end();
		}

	}

}
